<script setup lang="ts">
import { delay } from "@pureadmin/utils";
import { ref, onMounted, reactive, watchEffect, h, onUnmounted } from "vue";
import {
  PaginationProps,
  LoadingConfig,
  Align,
  PureTable
} from "@pureadmin/table";
import { ElTag, ElMessage, ElMessageBox, ElButton } from "element-plus";
import { getRegisterLog } from "@/api/routes";

// 数据列表和加载状态
const dataList = ref([]);
const loading = ref(true);
const tableSize = ref("default");
const paginationAlign = ref("right");

// 筛选条件
const filters = reactive({
  devId: "",
  errorMessage: ""
});

// 多选相关状态
const selectedRows = ref([]);

// 优化后的表格列定义
const columns = [
  {
    type: "selection",
    align: "left",
    reserveSelection: true
  },
  {
    label: "ID",
    prop: "id",
    width: 80,
    sortable: true
  },
  {
    label: "设备ID",
    prop: "dev_id",
    width: 300
  },
  {
    label: "注册状态",
    prop: "success",
    width: 100,
    cellRenderer: ({ row }) => {
      return h(
        ElTag,
        {
          type: row.success ? "success" : "danger",
          effect: "dark"
        },
        row.success ? "成功" : "失败"
      );
    }
  },
  {
    label: "注册时间",
    prop: "registration_time",
    width: 180,
    cellRenderer: ({ row }) => {
      // 格式化时间显示
      const date = new Date(row.registration_time);
      return date.toLocaleString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit"
      });
    }
  },
  {
    label: "错误信息",
    prop: "error_message",
    width: 200,
    cellRenderer: ({ row }) => {
      return row.error_message || "-";
    }
  },
  {
    label: "IP地址",
    prop: "ip_address",
    width: 140
  }
];

/** 分页配置 */
const pagination = reactive<PaginationProps>({
  pageSize: 10,
  currentPage: 1,
  pageSizes: [10, 20, 50],
  total: 0,
  align: "right",
  background: true,
  size: "default"
});

/** 加载动画配置 */
const loadingConfig = reactive<LoadingConfig>({
  text: "正在加载注册日志数据...",
  viewBox: "-10, -10, 50, 50",
  spinner: `
      <path class="path" d="
        M 30 15
        L 28 17
        M 25.61 25.61
        A 15 15, 0, 0, 0, 15 30
        A 15 15, 0, 1, 0, 27.99 7.5
        L 15 15
      " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
    `
});

// 分页大小变化
function onSizeChange(val: number) {
  pagination.pageSize = val;
  pagination.currentPage = 1;
  loadData();
}

// 当前页变化
function onCurrentChange(val: number) {
  pagination.currentPage = val;
  loadData();
}

// 筛选方法
function applyFilters() {
  pagination.currentPage = 1;
  loadData();
}

// 重置筛选条件
function resetFilters() {
  Object.keys(filters).forEach(key => {
    filters[key] = "";
  });
  applyFilters();
}

// 批量更新方法
function batchUpdate() {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要操作的日志");
    return;
  }

  ElMessageBox.confirm(
    `确定要对选中的 ${selectedRows.value.length} 条日志执行操作吗？`,
    "确认操作",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  ).then(() => {
    loading.value = true;
    // 模拟批量操作API调用
    delay(1000).then(() => {
      loading.value = false;
      ElMessage.success("操作已提交");
      selectedRows.value = [];
    });
  });
}

// 从后端API获取注册日志数据
async function fetchRegistrationLogs() {
  try {
    const result = await getRegisterLog();

    // 确保返回的是数组格式
    if (Array.isArray(result)) {
      return result;
    } else if (Array.isArray(result.data)) {
      return result.data;
    } else if (Array.isArray(result.result)) {
      return result.result;
    } else {
      throw new Error("API返回的数据格式不正确");
    }
  } catch (error) {
    console.error("获取注册日志失败:", error);
    ElMessage.error("获取注册日志失败");
    return [];
  }
}

// 加载数据方法
async function loadData() {
  loading.value = true;
  loadingConfig.text = `正在加载注册日志数据...`;

  try {
    const apiData = await fetchRegistrationLogs();

    if (!Array.isArray(apiData)) {
      throw new Error("API返回的数据不是数组格式");
    }

    // 按ID从大到小排序
    const sortedData = apiData.sort((a, b) => b.id - a.id);

    // 应用筛选条件
    const filteredData = sortedData.filter(item => {
      return (
        (filters.devId ? item.dev_id.includes(filters.devId) : true) &&
        (filters.errorMessage
          ? item.error_message &&
            item.error_message.includes(filters.errorMessage)
          : true)
      );
    });

    // 更新分页总数
    pagination.total = filteredData.length;

    // 分页处理
    const start = (pagination.currentPage - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;
    dataList.value = filteredData.slice(start, end);

    console.log("加载注册日志数据完成", {
      total: pagination.total,
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize,
      dataCount: dataList.value.length
    });
  } catch (error) {
    console.error("加载注册日志数据出错:", error);
    ElMessage.error("加载注册日志数据失败: " + error.message);
  } finally {
    loading.value = false;
  }
}

watchEffect(() => {
  pagination.align = paginationAlign.value as Align;
});

onMounted(() => {
  console.log("开始加载注册日志数据...");
  loadData();
});
</script>

<template>
  <div class="device-management-container">
    <!-- 优化后的筛选栏目 -->
    <el-card class="mb-4 filter-card">
      <el-form :inline="true" :model="filters" class="filter-form">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="设备ID">
              <el-input
                v-model="filters.devId"
                placeholder="设备ID"
                clearable
                class="w-full"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-form-item label="错误信息">
              <el-input
                v-model="filters.errorMessage"
                placeholder="错误信息"
                clearable
                class="w-full"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="8">
            <el-form-item class="action-buttons">
              <el-button type="primary" icon="Search" @click="applyFilters">
                查询
              </el-button>
              <el-button icon="Refresh" @click="resetFilters"> 重置 </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card>
      <pure-table
        row-key="id"
        :loading="loading"
        :columns="columns"
        :data="dataList"
        :size="tableSize"
        :pagination="pagination"
        :loadingConfig="loadingConfig"
        @page-size-change="onSizeChange"
        @page-current-change="onCurrentChange"
        @selection-change="selectedRows = $event"
      >
        <template #header>
          <div class="table-header">
            <div class="text-lg font-medium">注册日志列表</div>
            <div>
              <el-button
                type="primary"
                :disabled="selectedRows.length === 0"
                icon="Refresh"
                @click="batchUpdate"
              >
                操作选中日志 ({{ selectedRows.length }})
              </el-button>
            </div>
          </div>
        </template>
      </pure-table>
    </el-card>
  </div>
</template>

<style scoped>
.device-management-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  width: 100%;
}

.el-form-item {
  margin-bottom: 0;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
}

@media (width <= 768px) {
  .el-col {
    margin-bottom: 10px;
  }

  .action-buttons {
    justify-content: center;
  }
}
</style>
